package com.rlz.framemm.util

import android.app.Activity
import android.content.Context
import android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP
import android.content.Intent.FLAG_ACTIVITY_NO_ANIMATION
import android.content.res.Configuration
import android.os.Process
import androidx.appcompat.app.AppCompatDelegate
import com.rlz.base.util.single.Single
import com.rlz.framemm.util.Constants.Companion.KEY_MODE_NIGHT
import com.rlz.framemm.util.Constants.Companion.KEY_MODE_SYSTEM

/**
 * Created by RLZ
 * on 2021/11/5
 *
 */
class NightManager {


    companion object : Single<NightManager>(::NightManager)

    fun isNightMode(context: Context): Boolean {
        return context.resources.configuration.uiMode and
                Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES
    }

    /**
     * 是否跟随系统
     */
    fun getSystemMode(): Boolean {
        return States.get().getBoolean(KEY_MODE_SYSTEM)
    }


    /**
     * 保存系统模式
     */
    fun setSystemMode(mode: Boolean) {
        States.get().save(KEY_MODE_SYSTEM, mode)
    }


    /**
     * 是否是深色模式
     */
    fun getNightMode(): Boolean {
        return States.get().getBoolean(KEY_MODE_NIGHT)
    }


    /**
     * 保存深色模式
     */
    fun setNightMode(mode: Boolean) {
        States.get().save(KEY_MODE_NIGHT, mode)
    }

    /**
     * 初始化
     */
    fun initNightMode() {
        initMode(getSystemMode(), getNightMode())
    }

    private fun initMode(systemMode: Boolean, nightMode: Boolean) {
        if (systemMode) {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
        } else {
            if (nightMode) {
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
            } else {
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
            }
        }
    }


    /**
     * 重启应用
     */
    fun restartApp(activity: Activity) {
        val intent =
            activity.packageManager.getLaunchIntentForPackage(activity.packageName)
        intent.let {
            it?.addFlags(FLAG_ACTIVITY_CLEAR_TOP)
            it?.addFlags(FLAG_ACTIVITY_NO_ANIMATION)
            activity.startActivity(it)
            Process.killProcess(Process.myPid())
        }
    }

}